<template>
  <div>
    <el-dialog :title="title" :visible.sync="visible" width="600px" append-to-body custom-class="import-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" :disabled="userNameDisabled"/>
        </el-form-item>
        <el-form-item label="手机号" prop="phonenumber">
          <el-input v-model="form.phonenumber" placeholder="请输入手机号" maxlength="11" v-input.int
                    @input="checkUserMobile"
          />
          <span>手机号作为用户的登录账号，创建后密码默认123456</span>
        </el-form-item>
        <el-form-item label="所在部门" prop="deptId">
          <treeselect v-model="form.deptId" :options="treeDeptList" :normalizer="normalizer"
                      placeholder="选择上级部门"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select v-model="form.roleIds" placeholder="请选择" multiple>
            <el-option v-for="item in roleList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="区域标签">
          <el-radio-group v-model="form.bizTenantUser.areaLabel" @change="tagChange">
            <el-radio
              v-for="(item, index) in departmentTagList"
              :key="index"
              :label="item.value"
            >{{ item.label }}
            </el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="区域" v-if="form.bizTenantUser.areaLabel>1">
          <el-select
            v-if="form.bizTenantUser.areaLabel >= 2"
            v-model="form.bizTenantUser.provinceId"
            placeholder="省"
            size="small"
            style="width: 100px"
            @change="provinceChange"
          >
            <el-option
              v-for="(item, index) in provinceList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-if="form.bizTenantUser.areaLabel >= 3"
            v-model="form.bizTenantUser.cityId"
            placeholder="市"
            size="small"
            style="width: 100px; margin-left: 10px"
            @change="cityChange"
          >
            <el-option
              v-for="(item, index) in cityList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-if="form.bizTenantUser.areaLabel >= 4"
            v-model="form.bizTenantUser.districtId"
            placeholder="区"
            size="small"
            style="width: 100px; margin-left: 10px"
            @change="districtChange"
          >
            <el-option
              v-for="(item, index) in districtList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-if="form.bizTenantUser.areaLabel >= 5"
            v-model="form.bizTenantUser.streetId"
            placeholder="街道"
            size="small"
            style="width: 100px; margin-left: 10px"
            @change="streetChange"
          >
            <el-option
              v-for="(item, index) in streetList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-if="form.bizTenantUser.areaLabel >= 6"
            v-model="form.bizTenantUser.communityId"
            placeholder="社区"
            size="small"
            style="width: 100px; margin-left: 10px"
            @change="communityChange"
          >
            <el-option
              v-for="(item, index) in communityList"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="人脸照片" prop="faceImage" v-if="isHouseKeeper(form.roleIds)">
          <ImageUpload v-model="form.faceImage" :limit="1">
            <template slot="tip" slot-scope="props">
              <span style="color: red;font-size: 14px;">请上传正面头像照片</span>
            </template>
          </ImageUpload>

        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUserBusiness, updateUserBusiness, checkUserMobile } from '@/api/enterprise/user'
import { treeDeptList } from '@/api/enterprise/dept'
import { roleListByEnterprise } from '@/api/enterprise/role'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { debounce } from '@/utils'
import { listArea } from '@/api/system/config'

export default {
  props: {
    title: {
      default: '新增机构信息'
    },
    value: {
      default: false
    },
    data: {
      default: undefined
    }
  },
  components: { Treeselect },
  data() {
    return {
      visible: false,
      form: {
        bizTenantUser:{

        }
      },
      rules: {
        userName: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' }
        ],
        phonenumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          }
        ],
        roleId: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '角色不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ],
        faceImage: [
          { required: true, message: '请上传人脸照片', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ]
      },
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 总条数
      total: 0,
      //列表
      list: [],
      //角色列表
      roleList: [],
      //部门集合列表-树形结构
      treeDeptList: [],
      //用户名称禁止输入
      userNameDisabled: false,
      //省份列表
      provinceList: [],
      //市列表
      cityList: [],
      //区列表
      districtList: [],
      //街道列表
      streetList: [],
      //社区列表
      communityList: [],
      departmentTagList: [
        { label: '无', value: '1' },
        { label: '省', value: '2' },
        { label: '市', value: '3' },
        { label: '区', value: '4' },
        { label: '街道', value: '5' },
        { label: '社区', value: '6' }
      ]
    }
  },
  computed: {
    isHouseKeeper() {
      return (roleIds) => {
        // console.log(roleId)
        // let role = this.roleList.find(item => item.value == roleId)
        // console.log('role',role)
        // return role && role.roleKey === 'housekeeper'

        let roles = this.roleList.filter(item => roleIds.includes(item.value))
        // 判断是否有房管角色
        let housekeeper = roles.find(item => item.roleKey === 'housekeeper')
        return !!housekeeper
      }
    }
  },
  watch: {
    value(newVal, oldVal) {
      if (newVal) {
        this.init()
      }
      this.visible = newVal // 监测value的变化，并赋值。
    },
    visible(val) {
      this.$emit('input', val) // 此处监测visible目的为关闭弹窗时，重新更换value值，注意emit的事件一定要为input。
    }
  },
  created() {
    this.getProvinceList()
  },
  methods: {
    init() {
      this.reset()
      this.getRoleList()
      // this.getListDepartment()
      this.getTreeDeptList()
    },
    reset() {
      // this.dateRange = [];
      this.userNameDisabled = false
      this.form = {
        userName: '',
        phonenumber: undefined,
        roleId: undefined,
        roleIds: [],
        roles: [],
        faceImage: undefined,
        status: '0',
        deptId: undefined,
        bizTenantUser: {
          provinceId: '', //省份id
          provinceName: '', //省份名称
          cityId: '', //市id
          cityName: '', //市名称
          districtId: '', //区id
          districtName: '', //区名称
          streetId: '', //所属街道
          streetName: '', //街道名称
          communityId: '', //所属社区id
          communityName: '', //社区名称
          areaLabel: '1' //区域标签:1.无；2.省；3.市；4.区；5.街道；6.社区
        }
      }
      this.resetForm('form')
      for (const key in this.data) {
        if (Object.hasOwnProperty.call(this.data, key)) {
          this.form[key] = this.data[key]
        }
      }
      if (this.form.bizTenantUser.provinceId) {
        this.provinceChange(this.form.bizTenantUser.provinceId,'init');
      }
      if (this.form.bizTenantUser.cityId) {
        this.cityChange(this.form.bizTenantUser.cityId,'init');
      }
      if (this.form.bizTenantUser.districtId) {
        this.districtChange(this.form.bizTenantUser.districtId,'init');
      }
      if (this.form.bizTenantUser.streetId) {
        this.streetChange(this.form.bizTenantUser.streetId,'init');
      }
      if (this.form.bizTenantUser.communityId) {
        this.communityChange(this.form.bizTenantUser.communityId,'init');
      }
      this.form.roleIds = this.form.roles.map(item => item.roleId)
    },
    // 标签切换
    tagChange(val) {
      switch (val) {
        case '2':
          this.form.bizTenantUser.cityId = ''
          this.form.bizTenantUser.cityName = ''
          this.form.bizTenantUser.districtId = ''
          this.form.bizTenantUser.districtName = ''
          this.form.bizTenantUser.streetId = ''
          this.form.bizTenantUser.streetName = ''
          this.form.bizTenantUser.communityId = ''
          this.form.bizTenantUser.communityName = ''
          break
        case '3':
          this.form.bizTenantUser.districtId = ''
          this.form.bizTenantUser.districtName = ''
          this.form.bizTenantUser.streetId = ''
          this.form.bizTenantUser.streetName = ''
          this.form.bizTenantUser.communityId = ''
          this.form.bizTenantUser.communityName = ''
          break
        case '4':
          this.form.bizTenantUser.streetId = ''
          this.form.bizTenantUser.streetName = ''
          this.form.bizTenantUser.communityId = ''
          this.form.bizTenantUser.communityName = ''
          break
        case '5':
          this.form.bizTenantUser.communityId = ''
          this.form.bizTenantUser.communityName = ''
          break
        case '6':
          break
        default:
          break
      }
    },
    getProvinceList() {
      listArea({level: 1}).then(response => {
        this.provinceList = response.data
      })
    },
    //省变化
    provinceChange(val,type='update') {
      if (type === 'init') {

      }else{
        this.form.bizTenantUser.cityId = ''
        this.form.bizTenantUser.cityName = ''
        this.form.bizTenantUser.districtId = ''
        this.form.bizTenantUser.districtName = ''
        this.form.bizTenantUser.streetId = ''
        this.form.bizTenantUser.streetName = ''
        this.form.bizTenantUser.communityId = ''
        this.form.bizTenantUser.communityName = ''
        this.cityList = []
        this.districtList = []
        this.streetList = []
        this.communityList = []
        this.form.bizTenantUser.provinceName = this.provinceList.find(item => item.id === val).name
        this.$forceUpdate()
      }
      listArea({level: 2, parentId: val}).then(response => {
        this.cityList = response.data
      })
    },
    //市变化
    cityChange(val,type='update') {
      if(type === 'init'){}
      else{
        this.form.bizTenantUser.districtId = ''
        this.form.bizTenantUser.districtName = ''
        this.form.bizTenantUser.streetId = ''
        this.form.bizTenantUser.streetName = ''
        this.form.bizTenantUser.communityId = ''
        this.form.bizTenantUser.communityName = ''
        this.districtList = []
        this.streetList = []
        this.communityList = []
        this.form.bizTenantUser.cityName = this.cityList.find(item => item.id === val).name
        this.$forceUpdate()
      }

      listArea({ level: 3, parentId: val }).then(response => {
        this.districtList = response.data
      })
    },
    //区变化
    districtChange(val,type='update') {
      if(type === 'init'){}
      else{
        this.form.bizTenantUser.streetId = ''
        this.form.bizTenantUser.streetName = ''
        this.form.bizTenantUser.communityId = ''
        this.form.bizTenantUser.communityName = ''
        this.streetList = []
        this.communityList = []
        this.form.bizTenantUser.districtName = this.districtList.find(item => item.id === val).name
        this.$forceUpdate()
      }
      listArea({ level: 4, parentId: val }).then(response => {
        this.streetList = response.data
      })
    },
    //街道变化
    streetChange(val,type='update') {
      if(type === 'init'){}
      else{
        this.form.bizTenantUser.communityId = ''
        this.form.bizTenantUser.communityName = ''
        this.communityList = []
        this.form.bizTenantUser.streetName = this.streetList.find(item => item.id === val).name
        this.$forceUpdate()
      }
      listArea({ level: 5, parentId: val }).then(response => {
        this.communityList = response.data
      })
    },
    //社区变化
    communityChange(val,type='update') {
      if(type === 'init'){}
      else{
        this.form.bizTenantUser.communityName = this.communityList.find(item => item.id === val).name
        this.$forceUpdate()
      }

    },
    getTreeDeptList() {
      treeDeptList().then(response => {
        this.treeDeptList = response.data
      })
    },
    //获取角色列表
    getRoleList() {
      roleListByEnterprise().then(response => {
        this.roleList = response.data.map(item => {
          return {
            value: item.roleId,
            label: item.roleName,
            roleKey: item.roleKey
          }
        })
      })
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.userId) {
            updateUserBusiness(this.form).then(response => {
              if (response.code == 200) {
                this.$emit('success')
                this.$message.success(response.msg)
                this.visible = false
              } else {
                this.$message.error(response.msg)
              }
            })
          } else {
            addUserBusiness(this.form).then(response => {
              if (response.code == 200) {
                this.$emit('success')
                this.$message.success(response.msg)
                this.visible = false
              } else {
                this.$message.error(response.msg)
              }
            })
          }
        }
      })
    },
    cancel() {
      this.reset()
      this.visible = false
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      if (node.children == null || node.children == 'null') {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    //检查用户手机号是否存在
    checkUserMobile: debounce(function() {
      let phoneNumber = this.form.phonenumber
      var regex = /^[1][3-9]\d{9}$/
      if (phoneNumber.length < 11) {
        if (this.userNameDisabled) {
          this.form.userName = ''
        }
        this.userNameDisabled = false
        return
      }
      if (!regex.test(phoneNumber)) {
        this.$message.error('请输入正确的手机号码')
        return
      }
      checkUserMobile(phoneNumber).then(res => {
        if (res.code == 200) {
          if (res.state) {
            this.form.userName = res.userName
            this.userNameDisabled = true
          }
          // else {
          //   this.userNameDisabled = false
          //   this.form.userName = ''
          // }
        } else {
          this.$message.error('异常')
        }
      }).catch(err => {
        this.$message.error('网络异常')
      })
    }, 500)
  }
}
</script>

<style lang="scss" scoped>
@import "~@/assets/styles/dialog.scss";
</style>
